package cn.com.cetccst.dataupload.sync.compliance;

import static java.util.stream.Collectors.toList;
import static cn.com.cetccst.dataupload.sync.compliance.UploadComplianceWorker.DATA_LATEST_DATE;

import android.content.Context;

import androidx.lifecycle.LiveData;
import androidx.work.Data;
import androidx.work.ExistingWorkPolicy;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

import cn.com.cetccst.datacenter.policy.PolicyRepository;
import cn.com.cetccst.datacenter.policy.entity.ComplianceEntity;
import cn.com.cetccst.datacenter.policy.entity.ComplianceRecordEntity;
import cn.com.cetccst.dataupload.tools.WorkerUtil;
import cn.com.cetccst.tools.log.CommonLogger;

public class ComplianceRecordManager {

    private static ComplianceRecordManager instance;
    private final LiveData<List<ComplianceEntity>> complianceStatusList;
    private final LiveData<Long> recordDate;

    //内存级，如果应用重启会重新上传一次合规性
    private List<ComplianceEntity> previousData;

    private ComplianceRecordManager(Context context) {
        previousData = new ArrayList<>();
        complianceStatusList = PolicyRepository.getInstance().getAllCompliance();
        //动态监听合规性状态的变化，差异性持久化同步表，进而上报服务端
        complianceStatusList.observeForever(complianceEntities -> {
            //协议需要全部保存
            if (complianceEntities != null
                    && !complianceEntities.isEmpty()
                    && !previousData.equals(complianceEntities)) {
                CommonLogger.info("begin to record compliance data");
                List<ComplianceRecordEntity> syncEntities = complianceEntities.stream().map(new Function<ComplianceEntity, ComplianceRecordEntity>() {
                    final long time = System.currentTimeMillis();

                    @Override
                    public ComplianceRecordEntity apply(ComplianceEntity complianceEntity) {
                        ComplianceRecordEntity entity = new ComplianceRecordEntity();
                        entity.setDate(time);
                        entity.setKey(complianceEntity.getKey());
                        entity.setPunish(complianceEntity.getPunish());
                        entity.setStatus(complianceEntity.getStatus());
                        return entity;
                    }
                }).collect(toList());
                PolicyRepository.getInstance().saveComplianceRecords(syncEntities);
                //记录本次的存储
                previousData = complianceEntities;
            }
        });

        recordDate = PolicyRepository.getInstance().getLatestDateInComplianceRecord();
        recordDate.observeForever(date -> {
            if (date == null)
                return;
            CommonLogger.info("the latest date of compliance data " + date);
//            long[] dateArray = dates.stream().mapToLong(value -> value).toArray();
            Data data = new Data.Builder()
                    .putLong(DATA_LATEST_DATE, date)
                    .build();

            OneTimeWorkRequest workRequest = WorkerUtil.getOneTimeWorkRequest(UploadComplianceWorker.class, data);

//          WorkManager.getInstance(context).enqueueUniqueWork("UploadCompliance", ExistingWorkPolicy.APPEND_OR_REPLACE, workRequest);
            WorkManager.getInstance(context).enqueueUniqueWork("UploadCompliance", ExistingWorkPolicy.REPLACE, workRequest);
        });
    }

    public static void initialize(Context context) {
        if (instance == null) {
            instance = new ComplianceRecordManager(context);
        }

    }

    public static ComplianceRecordManager getInstance() {
        return instance;
    }
}
